const requireEx = require('yi-require');
const fs = require('fs');

const middleware = (req, res, next) => {
    let projectId = req.body.projectId;
    let id = req.body._id;
    if (projectId) {
        req.mongo.collection('file').findOne({_id: id}, (e, r) => {
            if (!r)
                return res.reply({code: 20003, message: "未找到文件信息"});
            if (r.static === 1) {
                let originalPath = r.url.replace(req.config.sys.resHost + '/', './');
                let newPath = '';
                if (r.projectId) {
                    newPath = originalPath.replace(r.projectId.toString(), projectId.toString());
                } else if (originalPath.indexOf('./static') === 0) {
                    newPath = originalPath.replace('./static/', '/static/' + projectId.toString() + '/');
                } else {
                    newPath = originalPath.replace('./uploadDir/', '/static/' + projectId.toString() + '/');
                }
                fs.rename('.' + originalPath, '.' + newPath, function (err) {
                    if (err) return res.reply({code: 20002, message: err});
                    req.body.url = req.config.sys.resHost + newPath;
                    next();
                })
            } else {
                next();
            }


        });
    } else
        next();

};

module.exports = {
    open: false,
    description: '更新上传信息',
    middleware: middleware,
    handler: requireEx('yi-restful').u('file')
};
